<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleTaskIn" :disabled="btnIsDisabled"> 按任务登记</a-button>
        <a-button type="primary" @click="handlePersonIn" :disabled="btnIsDisabled"> 按人员登记</a-button>
        <a-button type="primary" @click="handleTwoIn" :disabled="btnIsDisabled"> 二维表登记</a-button>
        <a-button type="primary" @click="handleExport" preIcon="ant-design:export-outlined">导出模板</a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
    <!--按任务登记弹窗-->
    <OrderTaskModal @register="registerOrderTaskModal" @success="handleSuccess" />
    <!--按人员登记弹窗-->
    <!--按二维表登记弹窗-->
    <!--安管系统导入弹窗-->
    <!-- 数据中台弹窗 -->
    <!-- 
      <TaskModal @register="registerTaskModal" :key="taskKey" @success="handleSuccess" />
    <person-modal @register="registerPersonModal" @success="handleSuccess" />
    <two-modal @register="registerTwoModal" @success="handleSuccess" />
    <system-modal @register="registerSystemModal" @success="handleSuccess" />
    <middle-modal @register="registerMiddleModal" @success="handleSuccess" /> -->
  </div>
</template>

<script name="emp-team-checkIn3-HubTeamResultOrder" setup>
import { ref, onMounted, onUnmounted, provide, reactive, nextTick, watchEffect, computed, unref, watch, defineComponent } from 'vue';
import { BasicTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage'
import { columns, searchFormSchema } from './HubTeamResultWork.data';
import { list, deleteOne, editTask, haveTwoData, getExportUrl, getImportUrl, deleteBatch } from './HubTeamResultWork.api';
import { getPeriodTree, getMonitoringStatus } from '/@/api/common/api';
import { Modal } from 'ant-design-vue';
import dayjs from 'dayjs';
import OrderTaskModal from './orderTaskModal.vue';


/* 
import TaskModal from './taskModal.vue';
import PersonModal from './personModal.vue';
import TwoModal from './twoModal.vue';
import MiddleModal from './middleModal.vue';
import SystemModal from './systemModal.vue'; */
// 轻提醒
import { useMessage } from '/@/hooks/web/useMessage';
const { createMessage: $message } = useMessage();
import { useUserStore } from '/@/store/modules/user';
const userStore = useUserStore();

//注册table数据
const { tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '工单工分积分',
    api: list,
    columns,
    canResize: false,
    showIndexColumn: true,
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [],
      fieldMapToTime: [],
    },
    actionColumn: {
      width: 120,
      fixed: 'right'
    },
    beforeFetch: (params) => {
      return Object.assign(params);
    },
  },
  exportConfig: {
    name: "工单工分积分",
    url: getExportUrl,
    // params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
})

const [registerTable, { getForm, reload, getDataSource, getColumns, setColumns, setTableData }, { rowSelection, selectedRows, selectedRowKeys }] = tableContext;



const [registerOrderTaskModal, { openModal: openOrderTaskModal = () => { } }] = useModal();


/* // 注册按任务工分登记弹窗
//注册按人员工分登记弹窗
const [registerTaskModal, { openModal: openTaskModal = () => { } }] = useModal();
const [registerPersonModal, { openModal: openPersonModal = () => { } }] = useModal();
//注册二维表登记弹窗
const [registerTwoModal, { openModal: openTwoModal = () => { } }] = useModal();
//注册安管系统弹窗
const [registerSystemModal, { openModal: openSystemModal = () => { } }] = useModal();
// 安管系统导入  数据中台
const [registerMiddleModal, { openModal: openMiddleModal = () => { } }] = useModal(); */

let pageParams = ref({
  orgCode: '',
  orgName: '',
  periodCode: '',
});

// 默认执行一次
const orgName = ref(userStore.getOrgName);
onMounted(async () => {
  let form = getForm();
  //获取编辑按钮的状态
  await getBtnStatus();
  // personList.value = await getBaseRelList({ orgCode: userStore.getOrgCode })
  form.updateSchema([
    {
      field: 'periodCode',
      label: '考核周期',
      component: 'ApiTreeSelect',
      componentProps: {
        api: getPeriodTree,
        fieldNames: {
          children: 'child',
          label: 'periodName',
          value: 'periodCode',
        },
        onChange: (e) => {
          handleSuccess();
        },
      },
    },
    {
      field: 'orgCode',
      componentProps: {
        onChange: (e, i) => {
          orgName.value = i?.label;
          handleSuccess();
        },
        // atfer request callback
        onOptionsChange: (options) => {
          console.log('get options', options.length, options);
        },
      },
    },
  ]);
});

//卸载组件触发
onUnmounted(() => {
  localStorage.removeItem('orgCode');
  localStorage.removeItem('periodCode');
});

const btnIsDisabled = ref(false);
// const orgOptionsList = [];

const handleExport = () => {
  // name, url, params, isXlsx = false, methods = 'get'
  let exportParams = {
    name: '工单工分模板',
    url: '/emp/hubTeamResultOrder/exportXls',
    params: {
      ...pointsList.value.getForm().getFieldsValue(),
      type: '1',
    },
  };
  exportXls({ ...exportParams });
};

let taskKey = computed(() => {
  return new Date().getTime() + 'task';
});
let tableSelectRecords = ref([]); //选中的表格行数据
const pointsList = ref(null); //列表页子组件对象
// let self = ref(''); //当前用户角色
// self.value = getPathKey(); // monitor班组长 leader负责人 self班员

const systemCheckIn = () => {
  if (!getForm().getFieldsValue().orgCode) {
    $message.error('请先选择班组!!');
    return;
  } else {
    let fromData = pointsList.value.getForm().getFieldsValue();
    /* openSystemModal(true, {
      // periodCode: fromData.periodCode,
      periodCode: '202306',
      orgCode: pageParams.value.orgCode,
      // orgName: pageParams.value.orgName,
    }); */
  }
};
// 二维表登记
const handleTwoIn = () => {
  if (!getForm().getFieldsValue().orgCode) {
    $message.error('请先选择班组!!');
    return;
  } else {
    // 因为二维表登记只能存在一条数据， 新增时需查询接口，若现已存在数据，则走编辑流程，无数据走新增。
    let fromData = pointsList.value.getForm().getFieldsValue();
    haveTwoData({
      orgCode: pageParams.value.orgCode,
      periodCode: fromData.periodCode,
    }).then((res) => {
      let transferData = {
        periodCode: fromData.periodCode,
        orgCode: pageParams.value.orgCode,
        orgName: pageParams.value.orgName,
      };
      if (res) {
        transferData.isEdit = true;
        transferData.res = res;
      } else {
        transferData.isEdit = false;
      }
      /* openTwoModal(true, transferData); */
    });
  }
};
//按任务登记按钮点击事件
const handleTaskIn = () => {
  if (!getForm().getFieldsValue().orgCode) {
    $message.error('请先选择班组!!');
    return;
  } else {
    console.log('pageParams123', pageParams);
    localStorage.setItem('orgCode', pageParams.value.orgCode); // todo：本地缓存班组编码，待后面优化
    localStorage.setItem('periodCode', pageParams.value.periodCode);


    openOrderTaskModal(true, {
      isEdit: false,
      orgName: orgName.value,
      ...getForm().getFieldsValue(),
    });
  }
};

//按人员登记按钮点击事件
const handlePersonIn = () => {
  if (!getForm().getFieldsValue().orgCode) {
    $message.error('请先选择班组!!');
    return;
  } else {
    let flag = 'pepCheck';
    localStorage.setItem('orgCode', pageParams.value.orgCode); // todo：本地缓存班组编码，待后面优化
    localStorage.setItem('periodCode', pageParams.value.periodCode);
    /* openPersonModal(true, {
      flag,
      isEdit: false,
      orgCode: pageParams.value.orgCode,
      orgName: pageParams.value.orgName,
      periodCode: pageParams.value.periodCode,
    }); */
  }
};

//表格选择事件
const tableSelect = (selectKeys) => {
  tableSelectRecords.value = [...selectKeys];
  let tableData = pointsList.value.getTableData(); //遍历表格数据判断选中的数据状态
  let flag = false; //审核状态
  let subFlag = false; //提交状态
  tableSelectRecords.value.forEach((k) => {
    tableData.forEach((d) => {
      // status 15为待审核 只有这个状态可审核
      if ('15' == d.status && k.id === d.id) {
        flag = true;
      }
      // status 14为待提交 17为退回 这2个状态可提交
      if (('17' == d.status || '14' == d.status) && k.id === d.id) {
        subFlag = true;
      }
    });
  });
};

//自定义表格编辑方法
const customEdit = (record, monitorCheck = false) => {
  let fromData = pointsList.value.getForm().getFieldsValue();
  localStorage.setItem('orgCode', pageParams.value.orgCode); // todo：本地缓存班组编码，待后面优化
  localStorage.setItem('periodCode', pageParams.value.periodCode);
  if ('10' == record.addMode) {
    //编辑按任务登记
    editTask({ id: record.id }).then((res) => {
      /* openTaskModal(true, {
        res,
        record,
        isEdit: true,
        periodCode: fromData.periodCode,
        orgCode: pageParams.value.orgCode,
        orgName: pageParams.value.orgName,
      }); */
      openOrderTaskModal(true, {
        res,
        record,
        isEdit: true,
        orgName: orgName.value,
        ...getForm().getFieldsValue(),
      });
    });
    return;
  } else if ('20' == record.addMode) {
    //编辑按人员登记
    editTask({ id: record.id }).then((res) => {
      /*  openPersonModal(true, {
         res,
         record,
         isEdit: true,
         periodCode: fromData.periodCode,
         orgCode: pageParams.value.orgCode,
         orgName: pageParams.value.orgName,
       }); */
    });
    return;
  } else if ('30' == record.addMode) {
    //编辑二维表登记
    editTask({ id: record.id }).then((res) => {
      /* openTwoModal(true, {
        res,
        record,
        isEdit: true,
        periodCode: fromData.periodCode,
        orgCode: pageParams.value.orgCode,
        orgName: pageParams.value.orgName,
      }); */
    });
    return;
  } else if ('30' == record.addMode) {
    //编辑二维表登记
    editTask({ id: record.id }).then((res) => {
      /* openTwoModal(true, {
        res,
        record,
        isEdit: true,
        periodCode: fromData.periodCode,
        orgCode: pageParams.value.orgCode,
        orgName: pageParams.value.orgName,
      }); */
    });
    return;
  }
  //编辑按人员登记
  // editTask({ id: record.id }).then((res) => {
  //   openPepEditModal(true, {
  //     res,
  //     record,
  //     monitorCheck,
  //   });
  // });
};
//查看
const customCheck = (record) => {
  localStorage.setItem('orgCode', pageParams.value.orgCode); // todo：本地缓存班组编码，待后面优化
  localStorage.setItem('periodCode', pageParams.value.periodCode);
  let fromData = pointsList.value.getForm().getFieldsValue();
  if ('10' == record.addMode) {
    //编辑按任务登记
    editTask({ id: record.id }).then((res) => {
      /* openTaskModal(true, {
        res,
        record,
        isEdit: true,
        isView: true,
        periodCode: fromData.periodCode,
        orgCode: pageParams.value.orgCode,
        orgName: pageParams.value.orgName,
      }); */
    });
    return;
  } else if ('20' == record.addMode) {
    //编辑按人员登记
    editTask({ id: record.id }).then((res) => {
      /* openPersonModal(true, {
        res,
        record,
        isEdit: true,
        isView: true,
        periodCode: fromData.periodCode,
        orgCode: pageParams.value.orgCode,
        orgName: pageParams.value.orgName,
      }); */
    });
    return;
  } else if ('30' == record.addMode) {
    //编辑二维表登记
    editTask({ id: record.id }).then((res) => {
      /* openTwoModal(true, {
        res,
        record,
        isEdit: true,
        isView: true,
        periodCode: fromData.periodCode,
        orgCode: pageParams.value.orgCode,
        orgName: pageParams.value.orgName,
      }); */
    });
    return;
  } else if ('40' == record.addMode) {
    editTask({ id: record.id }).then((res) => {
      /*  openMiddleModal(true, {
         res,
         record,
         isEdit: true,
         isView: true,
         periodCode: fromData.periodCode,
         orgCode: pageParams.value.orgCode,
         orgName: pageParams.value.orgName,
       }); */
    });
  }
};

//自定义删除方法
const customDelete = (record) => {
  deleteBatch(record.id).then((res) => {
    console.log('res', res);
    pointsList.value.reload();
  });
};

//当前周期
// const currentMoth = () => {
//   const year = new Date().getFullYear();
//   let month = new Date().getMonth() + 1;
//   if (10 > month) {
//     // @ts-ignore
//     month = '0' + month;
//   }
//   return year + month;
// };

//下发方法
provide('customEdit', customEdit);
provide('customDelete', customDelete);
provide('customCheck', customCheck);

/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}

/**
 * 成功回调
 */
async function handleSuccess() {
  //查看按钮组操作状态
  await getBtnStatus();
  //重置编辑状态
  (selectedRowKeys.value = []) && reload();
}

const getBtnStatus = () => {
  getMonitoringStatus({
    orgCode: getForm().getFieldsValue().orgCode,
    periodCode: getForm().getFieldsValue().periodCode,
  }).then((res) => {
    btnIsDisabled.value = res.data == '2';
  });
};

/**
 * 同步数据库表字段事件
 */
async function handleGenColumn(ss, record) {
  $message.info("123");
}

/**
 * 操作栏
 */
function getTableAction(record, index) {
  return [
    {
      label: '编辑',
      onClick: handleGenColumn.bind(null, record)
    },
    {
      label: '查看',
      onClick: handleGenColumn.bind(null, record)
    },
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record, index),
      },
      disabled: btnIsDisabled.value,
    },
  ];
}
</script>

<style lang="less" scoped>
.ant-picker {
  width: 100%;
}

.btn {
  margin-left: 12px;
}

/deep/.ant-table-wrapper {
  padding: 16px !important;
}
</style>
